package com.cennavi.minemapdemo.adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.cennavi.minemapdemo.R;
import com.cennavi.minemapdemo.offline.BaseViewHolder;
import com.cennavi.minemapdemo.offline.IOfflineListener;
import com.cennavi.minemapdemo.offline.OfflinDownItem;
import com.cennavi.minemapdemo.offline.OfflineListenerAdpter;
import com.cennavi.minemapdemo.offline.OfflineUtil;
import com.cennavi.minemapdemo.util.FileUtil;
import com.minedata.minemap.offline.OfflineDataManager;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Created by lijingru on 2019/7/2.
 */
public class OfflineDownAdapter extends RecyclerView.Adapter<BaseViewHolder>  {
    private List<OfflinDownItem> list;
    private Context mContext;
    private LayoutInflater mInflater;

    public OfflineDownAdapter(List<OfflinDownItem> list, Context mContext) {
        this.list = list;
        this.mContext = mContext;
        this.mInflater = LayoutInflater.from(mContext);
    }

    @NonNull
    @Override
    public BaseViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {


        View view = null;
        switch (viewType) {
            case OfflineUtil.PARENT_ITEM:
                view = mInflater.inflate(R.layout.down_item_parent, parent, false);
                return new ParentViewHolder(mContext, view);
            case OfflineUtil.PARENT_ITEM_NO_CHILD:
                view = mInflater.inflate(R.layout.down_item_parent, parent, false);
                return new ParentViewHolder(mContext, view);
            case OfflineUtil.CHILD_ITEM:
                view = mInflater.inflate(R.layout.down_item_child, parent, false);
                return new ChildViewHolder(mContext, view);
            default:
                view = mInflater.inflate(R.layout.down_item_parent, parent, false);
                return new ParentViewHolder(mContext, view);
        }

    }

    @Override
    public void onBindViewHolder(@NonNull BaseViewHolder holder, int position) {

        switch (getItemViewType(position)) {
            case OfflineUtil.PARENT_ITEM: {
                ParentViewHolder parentViewHolder = (ParentViewHolder) holder;
                OfflinDownItem bean = list.get(position);
                bean.setID(position + "");
                parentViewHolder.bindView(list.get(position), position, mListeners);
            }
            break;
            case OfflineUtil.PARENT_ITEM_NO_CHILD: {
                ParentViewHolder parentViewHolder = (ParentViewHolder) holder;
                parentViewHolder.bindViewDown(list.get(position), position, mListeners);
            }
            break;
            case OfflineUtil.CHILD_ITEM:
                ChildViewHolder childViewHolder = (ChildViewHolder) holder;
                childViewHolder.bindView(list.get(position), mListeners);
                break;
        }
    }

    @Override
    public int getItemCount() {
        if (list != null && list.size()>0){

            return list.size();
        }
        return 0;
    }

    @Override
    public int getItemViewType(int position) {
        return list.get(position).getType();
    }

    private ArrayList<IOfflineListener> mListeners = null;

    public void addListener(IOfflineListener listener) {
        if (mListeners == null) {
            mListeners = new ArrayList<>();
        }
        mListeners.add(listener);
    }

    /**
     * Removes a listener from the set listening to this animation.
     *
     * @param listener the listener to be removed from the current set of listeners for this
     *                 animation.
     */
    public void removeListener(IOfflineListener listener) {
        if (mListeners == null) {
            return;
        }
        mListeners.remove(listener);
        if (mListeners.size() == 0) {
            mListeners = null;
        }
    }


    private OfflineListenerAdpter itemClickListener = new OfflineListenerAdpter() {
        @Override
        public void onExpandChildren(OfflinDownItem bean) {
            int position = getCurrentPosition(bean.getID());//确定当前点击的item位置
            List<OfflinDownItem> childrens = bean.getChildBean();//获取要展示的子布局数据对象，注意区分onHideChildren方法中的getChildBean()。
            if (childrens == null || childrens.size() == 0) {
                return;
            }
            List<OfflinDownItem> childrensCopy = new ArrayList<>(childrens);
            Collections.reverse(childrensCopy);
            for (int i = 0; i < childrensCopy.size(); i++) {
                OfflinDownItem children = childrensCopy.get(i);
                add(children, position + 1);//在当前的item下方插入
            }

            if (position == list.size() - 2 && mListeners != null && mListeners.size()>0) { //如果点击的item为最后一个
                for (IOfflineListener mListener : mListeners) {
                    mListener.onScrollTo(position + 1);//向下滚动，使子布局能够完全展示
                }

            }
        }

        @Override
        public void onHideChildren(OfflinDownItem bean) {
            int position = getCurrentPosition(bean.getID());//确定当前点击的item位置
            List<OfflinDownItem> childrens = bean.getChildBean();//获取子布局对象
            if (childrens == null || childrens.size() == 0) {
                return;
            }
            for (int i = 0; i < childrens.size(); i++) {
                remove(position + 1);//删除
            }
            if (mListeners != null && mListeners.size()>0) {
                for (IOfflineListener mListener : mListeners) {
                    mListener.onScrollTo(position);
                }
            }
        }

    };

    /**
     * 在父布局下方插入一条数据
     *
     * @param bean
     * @param position
     */
    public void add(OfflinDownItem bean, int position) {
        list.add(position, bean);
        notifyItemInserted(position);
    }

    /**
     * 确定当前点击的item位置并返回
     *
     * @param uuid
     * @return
     */
    protected int getCurrentPosition(String uuid) {
        for (int i = 0; i < list.size(); i++) {
            if (uuid.equalsIgnoreCase(list.get(i).getID())) {
                return i;
            }
        }
        return -1;
    }

    /**
     * 移除子布局数据
     *
     * @param position
     */
    protected void remove(int position) {
        list.remove(position);
        notifyItemRemoved(position);
    }






    class ParentViewHolder extends BaseViewHolder {
        private TextView name, info, size, state;
        private ImageView image, arrowImage;
        private View content, downLayout;
        private Context mContext;
        private ProgressBar progressBar;
        private TextView progressNumber;


        public ParentViewHolder(Context context, View itemView) {
            super(itemView);
            this.mContext = context;
            name = (TextView) itemView.findViewById(R.id.name);
            info = (TextView) itemView.findViewById(R.id.info);
            state = (TextView) itemView.findViewById(R.id.state);
            size = (TextView) itemView.findViewById(R.id.size);
            image = (ImageView) itemView.findViewById(R.id.image);
            arrowImage = (ImageView) itemView.findViewById(R.id.arrow_icon);
            downLayout = itemView.findViewById(R.id.down_layout);
            content = itemView.findViewById(R.id.content);
            progressBar = itemView.findViewById(R.id.progressBar);
            progressNumber = itemView.findViewById(R.id.progressNumber);


        }

        public void bindView(final OfflinDownItem bean, int position, final ArrayList<IOfflineListener> listeners) {
            name.setText(bean.getName());
            if (!TextUtils.isEmpty(bean.getInfo())) {
                info.setText(bean.getInfo());
                info.setVisibility(View.VISIBLE);
            } else {
                info.setVisibility(View.GONE);
            }
            downLayout.setVisibility(View.GONE);
            arrowImage.setVisibility(View.VISIBLE);
            progressBar.setVisibility(View.GONE);
            progressNumber.setVisibility(View.GONE);
            if (bean.isExpand()) {
                arrowImage.setRotation(180);
            } else {
                arrowImage.setRotation(0);
            }
            //父布局OnClick监听
            content.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (listeners != null && listeners.size()>0) {
                        for (IOfflineListener listener : listeners) {
                            if (bean.isExpand()) {
                                listener.onHideChildren(bean);
                                bean.setExpand(false);
                                closeArrow(arrowImage);
                            } else {
                                listener.onExpandChildren(bean);
                                bean.setExpand(true);
                                openArrow(arrowImage);
                            }
                        }
                    }
                }
            });
        }

        public void bindViewDown(final OfflinDownItem bean, int position, final ArrayList<IOfflineListener> listeners) {
            downLayout.setVisibility(View.VISIBLE);
            arrowImage.setVisibility(View.GONE);
            name.setText(bean.getName());
            if (!TextUtils.isEmpty(bean.getInfo())){
                info.setText(bean.getInfo());
                info.setVisibility(View.VISIBLE);
            }else {
                info.setVisibility(View.GONE);
            }
            progressBar.setVisibility(View.VISIBLE);
            progressNumber.setVisibility(View.VISIBLE);
            progressNumber.setText(bean.getPrNumber() + "%");
            progressBar.setProgress(bean.getPrNumber());

            switch (bean.getState()){
                case OfflineDataManager.Status.START:
                    state.setText("正在下载");
                    setDownLayoutColor(ContextCompat.getColor(mContext, R.color.colorBlue));
                    image.setImageResource(R.mipmap.offline_down_pause);
                    image.setVisibility(View.VISIBLE);
                    size.setText(FileUtil.getFormatSize(bean.getDownloadSize())+"/"+FileUtil.getFormatSize(bean.getSize()));
                    break;
                case OfflineDataManager.Status.COMPLETED:
                    state.setText("已下载");
                    setDownLayoutColor(ContextCompat.getColor(mContext, R.color.colorGrey));
                    image.setVisibility(View.GONE);
                    progressBar.setVisibility(View.GONE);
                    progressNumber.setVisibility(View.GONE);
                    size.setText(FileUtil.getFormatSize(bean.getSize()));
                    break;
                case OfflineDataManager.Status.UPDATE:
                    state.setText("正在更新");
                    setDownLayoutColor(ContextCompat.getColor(mContext, R.color.colorBlue));
                    image.setImageResource(R.mipmap.offline_down_pause);
                    image.setVisibility(View.VISIBLE);
                    size.setText(FileUtil.getFormatSize(bean.getDownloadSize())+"/"+FileUtil.getFormatSize(bean.getSize()));
                    break;
                case OfflineDataManager.Status.UPDATECOMPLETED:
                    state.setText("已更新");
                    setDownLayoutColor(ContextCompat.getColor(mContext, R.color.colorGrey));
                    image.setVisibility(View.GONE);
                    progressBar.setVisibility(View.GONE);
                    progressNumber.setVisibility(View.GONE);
                    size.setText(FileUtil.getFormatSize(bean.getSize()));
                    break;
                case OfflineDataManager.Status.PAUSE:
                    state.setText("已暂停");
                    setDownLayoutColor(ContextCompat.getColor(mContext, R.color.colorRed));
                    image.setImageResource(R.mipmap.offline_down_start_red);
                    image.setVisibility(View.VISIBLE);
                    size.setText(FileUtil.getFormatSize(bean.getDownloadSize())+"/"+FileUtil.getFormatSize(bean.getSize()));
                    break;
                case OfflineDataManager.Status.INIT:
                case OfflineDataManager.Status.FAIL:
                default:
                    state.setText("");
                    size.setTextColor(ContextCompat.getColor(mContext, R.color.colorGrey));
                    image.setImageResource(R.mipmap.offline_down_start_blue);
                    image.setVisibility(View.VISIBLE);
                    progressBar.setVisibility(View.GONE);
                    progressNumber.setVisibility(View.GONE);
                    size.setText(FileUtil.getFormatSize(bean.getSize()));
                    break;

            }
            downLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (listeners != null&& listeners.size()>0) {
                        for (IOfflineListener listener : listeners) {
                            listener.onItemClick(bean);
                        }
                    }
                }
            });

        }

        private void setDownLayoutColor(int color) {
            state.setTextColor(color);
            size.setTextColor(color);
            progressNumber.setTextColor(color);
//            try {
//                Bitmap mBitmap = BitmapFactory.decodeResource(BaseActivty.gCurrentActivity.getResources(), R.mipmap.offline_down_start_blue);
//                image.setImageBitmap(BitmapProvider.tintBitmap(mBitmap, color));
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
        }

        public void openArrow(View view) {
            view.animate().setDuration(150).rotation(180);
        }

        public void closeArrow(View view) {
            view.animate().setDuration(150).rotation(0);
        }
    }


    class ChildViewHolder extends BaseViewHolder {
        private TextView name, info, size, state;
        private ImageView image;
        private View content;
        private ProgressBar progressBar;
        private TextView progressNumber;

        public ChildViewHolder(Context context, View itemView) {
            super(itemView);
            name = (TextView) itemView.findViewById(R.id.name);
            info = (TextView) itemView.findViewById(R.id.info);
            state = (TextView) itemView.findViewById(R.id.state);
            size = (TextView) itemView.findViewById(R.id.size);
            image = (ImageView) itemView.findViewById(R.id.image);
            content = itemView.findViewById(R.id.content);
            progressBar = itemView.findViewById(R.id.progressBar);
            progressNumber = itemView.findViewById(R.id.progressNumber);
        }

        public void bindView(final OfflinDownItem bean, final ArrayList<IOfflineListener> listeners) {
            name.setText(bean.getName());
            if (!TextUtils.isEmpty(bean.getInfo())) {
                info.setText(bean.getInfo());
                info.setVisibility(View.VISIBLE);
            } else {
                info.setVisibility(View.GONE);
            }
            progressBar.setVisibility(View.VISIBLE);
            progressNumber.setVisibility(View.VISIBLE);
            progressNumber.setText(bean.getPrNumber() + "%");
            progressBar.setProgress(bean.getPrNumber());
            switch (bean.getState()) {
                case OfflineDataManager.Status.START:
                    state.setText("正在下载");
                    setDownLayoutColor(ContextCompat.getColor(mContext, R.color.colorBlue));
                    image.setImageResource(R.mipmap.offline_down_pause);
                    image.setVisibility(View.VISIBLE);
                    size.setText(FileUtil.getFormatSize(bean.getDownloadSize())+"/"+FileUtil.getFormatSize(bean.getSize()));
                    break;
                case OfflineDataManager.Status.COMPLETED:
                    state.setText("已下载");
                    setDownLayoutColor(ContextCompat.getColor(mContext, R.color.colorGrey));
                    image.setVisibility(View.GONE);
                    progressBar.setVisibility(View.GONE);
                    progressNumber.setVisibility(View.GONE);
                    size.setText(FileUtil.getFormatSize(bean.getSize()));
                    break;
                case OfflineDataManager.Status.PAUSE:
                    state.setText("已暂停");
                    setDownLayoutColor(ContextCompat.getColor(mContext, R.color.colorRed));
                    image.setImageResource(R.mipmap.offline_down_start_red);
                    image.setVisibility(View.VISIBLE);
                    size.setText(FileUtil.getFormatSize(bean.getDownloadSize())+"/"+FileUtil.getFormatSize(bean.getSize()));
                    break;
                case OfflineDataManager.Status.INIT:
                case OfflineDataManager.Status.FAIL:
                default:
                    state.setText("");
                    size.setTextColor(ContextCompat.getColor(mContext, R.color.colorGrey));
                    image.setImageResource(R.mipmap.offline_down_start_blue);
                    image.setVisibility(View.VISIBLE);
                    progressBar.setVisibility(View.GONE);
                    progressNumber.setVisibility(View.GONE);
                    size.setText(FileUtil.getFormatSize(bean.getSize()));
                    break;

            }
            image.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (listeners != null && listeners.size()>0){
                        for (IOfflineListener listener : listeners) {
                            listener.onItemClick(bean);
                        }
                    }
                }
            });

            content.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    if (listeners != null && listeners.size()>0){
                        for (IOfflineListener listener : listeners) {
                            listener.onItemLongClick(bean);
                        }
                    }
                    return false;
                }
            });
        }

        private void setDownLayoutColor(int color) {
            state.setTextColor(color);
            size.setTextColor(color);
            progressNumber.setTextColor(color);
//            try {
//                Bitmap mBitmap = BitmapFactory.decodeResource(BaseActivty.gCurrentActivity.getResources(), R.mipmap.offline_down_start_blue);
//                image.setImageBitmap(BitmapProvider.tintBitmap(mBitmap, color));
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
        }
    }




}
